package com.nuanshui.heatedloan.middleware.mongodb;

import com.nuanshui.framework.utils.ReflectionUtils;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.GenericConverter;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.convert.CustomConversions;
import org.springframework.data.mongodb.core.convert.MongoConverter;

import java.util.Date;
import java.util.Iterator;
import java.util.Set;


/**
 * Mongo写数据不需要转换
 */
public class MongoConverterProcessor implements SmartInitializingSingleton {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void afterSingletonsInstantiated() {

        MongoConverter converter=(MongoConverter) ReflectionUtils.getFieldValue(mongoTemplate,"mongoConverter");

        if(converter==null)
           return;

        CustomConversions conversions=(CustomConversions)ReflectionUtils.getFieldValue(converter,"conversions");

        if(conversions==null)
            return;

        Set<GenericConverter.ConvertiblePair> writingPairs=(Set<GenericConverter.ConvertiblePair>)ReflectionUtils.getFieldValue(conversions,"writingPairs");

        if(writingPairs==null)
            return;

        for(Iterator<GenericConverter.ConvertiblePair> it = writingPairs.iterator(); it.hasNext();){
            GenericConverter.ConvertiblePair item = it.next();
            if (item.getSourceType() == Long.class && item.getTargetType() == Date.class) {
                it.remove();
            }
            else if (item.getSourceType() == Date.class && item.getTargetType() == Long.class) {
                it.remove();
            }
        }
    }
}
